// src/auth/quota-interceptor.interceptor.ts
import { Injectable, CallHandler, ExecutionContext, ForbiddenException, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { ApiKeyService } from '@/modules/api-key/api-key.service';

// 资源限额拦截器
@Injectable()
export class QuotaInterceptor implements NestInterceptor {
  constructor(private apiKeyService: ApiKeyService) { }

  async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
    const request = context.switchToHttp().getRequest();
    const { apiKey, apiKeyEntity } = request;

    // 检查资源限额
    if (apiKeyEntity.usedQuota >= apiKeyEntity.totalQuota) {
      throw new ForbiddenException('API key quota exceeded');
    }

    // 更新使用次数
    await this.apiKeyService.updateUsedQuota(apiKey);
    return next.handle();
  }
}